﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Toolkit.Web.Helpers;
using System.Web.Mvc;
using System.Web;

namespace Toolkit.Web.Mvc.ActionResults
{
    public class CustomJsonResult : JsonResult
    {
        public CustomJsonResult(object data)
            : base()
        {
            Data = data;
        }

        public CustomJsonResult(object data, JsonSerializationMethod method)
            : this(data)
        {
            SerializationMethod = method;
        }

        public JsonSerializationMethod SerializationMethod
        {
            get;
            set;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("GET not allowed.");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!string.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }

            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }

            if (Data != null)
            {
                response.Write(JsonSerialization.Serialize(Data, Data.GetType(), SerializationMethod));
            }
        }
    }
}
